package com.han.yrpc.core;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 单例工厂
 */
public class SingletonFactory {

    private static final Map<String, Object> SINGLETON_MAP = new ConcurrentHashMap<>();

    public static <T> T getSingleton(Class<T> tClass) {
        if (tClass == null) {
            throw new IllegalArgumentException();
        }

        String name = tClass.getName(); // com.han.yrpc.core.**

        Object singletonObject = SINGLETON_MAP.computeIfAbsent(name, t -> {
            try {
                return tClass.getDeclaredConstructor().newInstance();
            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        });
        return tClass.cast(singletonObject);
    }
}

